package cn.itcast.star.graph.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.jwt.JWTUtil;
import cn.itcast.star.graph.core.dto.request.UserLoginReqDTO;
import cn.itcast.star.graph.core.dto.respone.UserLoginResDTO;
import cn.itcast.star.graph.core.mapper.UserMapper;
import cn.itcast.star.graph.core.pojo.User;
import cn.itcast.star.graph.core.service.UserService;
import cn.itcast.star.graph.core.utils.JwtUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 登录
     * @param userLoginReqDTO
     * @return
     */
    @Override
    public UserLoginResDTO login(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        // 判断是否为空
        if (StringUtil.isEmpty(userLoginReqDTO.getUsername()) || StringUtil.isEmpty(userLoginReqDTO.getPassword())) {
            throw new BadRequestException("账号或密码不能为空");
        }

        User user = lambdaQuery()
                .or(StringUtil.isNotEmpty(userLoginReqDTO.getUsername()), c ->
                        c.eq(User::getMobile, userLoginReqDTO.getUsername()))
                .or(StringUtil.isNotEmpty(userLoginReqDTO.getUsername()), c ->
                        c.eq(User::getUsername, userLoginReqDTO.getUsername()))
                .one();
        if (user == null || !BCrypt.checkpw(userLoginReqDTO.getPassword(), user.getPassword()))
            throw new BadRequestException("账号或密码错误");
        return generateUserLoginResDTO(user);
    }

    private UserLoginResDTO generateUserLoginResDTO(User user) {
        UserLoginResDTO dto = BeanUtil.toBean(user, UserLoginResDTO.class);
        if (StringUtil.isEmpty(dto.getName()))
            dto.setName(user.getUsername());
        if (StringUtil.isEmpty(dto.getName()))
            dto.setName(user.getMobile());
        // 生成token
        dto.setToken(JwtUtils.createJwt(dto.getId(), dto.getName()));
        return dto;
    }
}
